
// 消费者接收日志消息
import * as amqp from "amqplib";
// RabbitMQ 服务器的连接信息
const rabbitMQServer = "amqp://mingcai_mq:EUDNfpZRbhfjb8PZ@95.169.25.181";
enum LogLevel {
    Error = "error",
    Warning = "warning",
    Info = "info",
}


async function receiveLogMessages(level: LogLevel) {
    try {
        // 创建 RabbitMQ 连接
        const connection = await amqp.connect(rabbitMQServer);
        const channel = await connection.createChannel();

        // 定义交换机名称
        const exchangeName = "logs_direct";

        // 声明 Direct 交换机
        await channel.assertExchange(exchangeName, "direct", { durable: false });

        // 声明队列
        const queue = await channel.assertQueue("", { exclusive: true });

        // 绑定队列到交换机，使用指定的路由键
        channel.bindQueue(queue.queue, exchangeName, level);

        // 接收日志消息
        console.log(`[*] Waiting for ${level} logs. To exit press CTRL+C`);
        channel.consume(
            queue.queue,
            (msg) => {
                if (msg && msg.content) {
                    console.log(`[x] Received ${level} log: ${msg.content.toString()}`);
                }
            },
            { noAck: true } // 不需要手动确认消息
        );
    } catch (error) {
        console.error("Error in receiveLogMessages:", error);
    }
}


if (process.env.LOG === 'all') {
    console.log('all log messages')
    receiveLogMessages(LogLevel.Error);
    receiveLogMessages(LogLevel.Warning);
    receiveLogMessages(LogLevel.Info);
}else {
    // 接收错误日志
    receiveLogMessages(LogLevel.Error);
}



